<template>
  <div>

    <div v-html="msg"></div>
    <h1>{{msg}}</h1>

    <h2 v-show="ok">hello world</h2>

    <div v-if="type === 'A'">A</div>
    <div v-else-if="type === 'B'">B</div>
    <div v-else>c</div>

    <ul>
      <li v-for="(item, index) in tlist" :class="{on:index%2==0, off:index%2!=0}">
        {{item.text}}, {{index}}
      </li>
    </ul>

    {{reverse_msg}}
    {{reverse_msg2()}}

    {{counter}}
    <button @click="counter++">点我加一</button>

    <br><br>
    <!--购物车-->
    <table border="1">
      <tr>
        <td>名称</td>
        <td>数量</td>
        <td>价格</td>
      </tr>

      <tr v-for="(item, index) in tlist">
        <td>
          {{item.text}}
        </td>
        <td>
          <button @click="minus(index,'-')">-</button>
          <input type="text" v-model="item.num">
          <button @click="minus(index,'+')">+</button>
        </td>
        <td>
          {{item.price}}
        </td>
      </tr>
    </table>
    总数量:{{totalCount()}}
    总价格:{{totalPrice()}}


  </div>

</template>

<script>
    export default {
        name: "test",
      //定义数据
      data(){
          return{
            msg: '这是一个变量',
            ok:1,
            type:'A',
            tlist:[{text:'汽车', num:1, price:20}, {text:'衣服',num:3, price:10}, {text:'手机', num:5, price:10}],
            counter:0,
          }
      },

      //监听属性
      watch:{
        counter:function (nval, oval) {
          console.log('计数器由'+oval+'变换为新的'+nval);
        }
      },

      //计算属性
      computed:{
        //反转
        reverse_msg:function () {
          console.log(this.msg.split(''));
          return this.msg.split('').reverse().join('');
        }
      },

      // 钩子方法 created
      mounted() {

      },

      //自定义方法
      methods:{
          //自定义反转属性
          reverse_msg2:function () {
          console.log(this.msg.split(''));
          return this.msg.split('').reverse().join('');
        },

        //购物车减法
        minus:function (index, type) {
          if(type==='-'){
            if(this.tlist[index].num > 0){
              this.tlist[index].num--;
            }
          }else {
            this.tlist[index].num++;
          }
        },
        //购物车加法
        // add:function (index) {
        //   this.tlist[index].num++;
        // },
        //汇总数量
        totalCount:function () {
          //默认数量
          let total = 0;
          //遍历
          for(let i=0, l=this.tlist.length; i<l; i++){
            //总数量累加
            total += this.tlist[i].num
          }
          return total;
        },
        //总价格
        totalPrice:function () {
          //默认数量
          let total = 0;
          //遍历
          for(let i=0, l=this.tlist.length; i<l; i++){
            //总数量累加
            total += (this.tlist[i].num*this.tlist[i].price)
          }
          return total;
        },

      }
    }
</script>

<style scoped>

  .on{background: #3B91FF;
      color: white;
  }
  .off{background: #E11617;
      color: black;
  }

</style>
